package com.superhelper.superhelper_web.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.superhelper.common.utils.CookieTools;
import com.superhelper.common.utils.CryptUtil;
import com.superhelper.common.utils.JsonHelper;
import com.superhelper.superhelper_web.common.CommonHelper;
import com.superhelper.superhelper_web.common.Consts;
import com.superhelper.superhelper_web.domain.AUserRole;
import com.superhelper.superhelper_web.domain.Admin;
import com.superhelper.superhelper_web.domain.AuserShopAudio;
import com.superhelper.superhelper_web.domain.PageModel;
import com.superhelper.superhelper_web.domain.Resource;
import com.superhelper.superhelper_web.domain.Role;
import com.superhelper.superhelper_web.domain.RoleResource;
import com.superhelper.superhelper_web.domain.TreeNode;
import com.superhelper.superhelper_web.mapper.AdminMapper;
import com.superhelper.superhelper_web.mapper.ResourceMapper;

@Service("adminService")
public class AdminService {

	/**
	 * 注入adminMapper
	 */
	@Autowired(required = true)
	private AdminMapper adminMapper;

	@Autowired(required = true)
	private ResourceMapper resourceMapper;

	/**
	 * 登录校验
	 * 
	 * @param username
	 *            用户名(必传)
	 * @param pwd
	 *            　　　　 密码　(必传)
	 * @param vcode
	 *            验证码 (可选)
	 * @param remenber
	 *            是否记住密码(可选)
	 * @param request
	 * @param response
	 * @return 　　　 校验结果
	 */
	public Map<String, String> login(String username, String pwd,
			String remenber, HttpServletRequest request,
			HttpServletResponse response) {

		// 从session中获取系统生成的验证码
		// String sessionCode = (String) request.getSession().getAttribute(
		// Consts.VERIFY_CODE);
		Map<String, String> result = new HashMap<>();

		try {
			// if (!sessionCode.equalsIgnoreCase(vcode)) {// 校验验证码
			// result.put("flag", "2");
			// result.put("tip", "验证码不正确");
			// } else {
			Admin admin = adminMapper.getAdminByUsername(username);// 从DB获取admin

			if (null != admin && admin.getPwd().equals(pwd)) {// 校验密码
				if ("1".equals(remenber)) { // 记住密码
					CookieTools.addCookie(response, Consts.COOKIE_ADMIN
							+ username, username, Consts.MAX_AGE);// 用户名放入cookie中
				}
				Date time = new Date();
				adminMapper.updateLoginAt(admin.getId(),time);
				admin.setLoginAt(time);
				request.getSession().setAttribute(Consts.SESSION_ADMIN, admin);
				result.put("flag", "1");
				result.put("tip", "登陆成功");
				result.put("userId", "" + admin.getId());
				// result.put("user", JsonHelper.toJson(admin));
			} else {
				result.put("flag", "0");
				result.put("tip", "帐号或密码不正确");
			}
			// }
		} catch (Exception e) {

		}
		return result;
	}

	/**
	 * 登录校验
	 * 
	 * @param username
	 *            用户名(必传)
	 * @param pwd
	 *            　　　　 密码　(必传)
	 * @param vcode
	 *            验证码 (可选)
	 * @param remenber
	 *            是否记住密码(可选)
	 * @param request
	 * @param response
	 * @return 　　　 校验结果
	 */
	public Map<String, String> register(String username, String pwd) {
		Map<String, String> result = new HashMap<>();
		try {
			Admin admin = adminMapper.getAdminByUsername(username);// 从DB获取admin
			if (null == admin) {// 校验密码
				admin = new Admin();
				admin.setUsername(username);
				admin.setPwd(pwd);
				admin.setStatus(0);
				admin.setRoleCode(0);
				admin.setEmail("");
				int res = adminMapper.addAdmin(admin);
				if (res > 0) {
					int roleId = 6;
					adminMapper.addUserRole(admin.getId(), roleId);
					CommonHelper.setSessionUser(admin);
					result.put("flag", "1");
					result.put("tip", "注册成功");
				} else {
					result.put("flag", "0");
					result.put("tip", "注册失败");
				}
			} else {
				result.put("flag", "0");
				result.put("tip", "注册失败，帐号已存在");
			}
		} catch (Exception e) {

		}
		return result;
	}

	/**
	 * 退出系统
	 */
	public void exit() {
		try {
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes()).getRequest();
			HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes()).getResponse();
			Admin user = CommonHelper.getSessionUser();
			request.getSession().removeAttribute(Consts.SESSION_ADMIN);// 移除session值
			CookieTools.removeCookie(response,
					Consts.COOKIE_ADMIN + user.getUsername());// 移除cookie值
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<Admin> getAdmin(int roleCode, int createId, PageModel pageModel) {
		int count = adminMapper.getAdminCount(roleCode, createId);
		pageModel.setRecordCount(count);
		return adminMapper.getAdmin(roleCode, createId, pageModel);
	}

	/**
	 * 获取用户对应的菜单资源
	 */
	public List<Resource> getMenuListByUserId(Integer userId) {

		Admin admin = adminMapper.getAdminById(userId);
		List<Resource> resources = null;
		if (admin.getRoleCode() != 2) {
			List<Integer> roleIds = this.getRoleIdByUserId(userId);
			if (!roleIds.isEmpty()) {
				resources = resourceMapper.getModelListByRoleId(StringUtils
						.join(roleIds, ","));
			}
		} else {
			resources = resourceMapper.getAllResource();
		}

		Map<Integer, List<Resource>> map = new TreeMap<>();
		Map<Integer, Resource> mapCache = new HashMap<>();
		List<Resource> list = null;
		for (Resource r : resources) {

			list = map.get(r.getParentId());
			if (list == null) {
				list = new ArrayList<Resource>();
				map.put(r.getParentId(), list);
			}
			if (!mapCache.containsKey(r.getId())) { // 过滤相同的资源
				mapCache.put(r.getId(), r);
				list.add(r);
			}
		}

		Set<Integer> set = map.keySet();
		Resource rr = null;
		List<Resource> result = new ArrayList<Resource>();
		for (Integer key : set) {
			rr = mapCache.get(key);
			if (rr != null) {
				rr.setSub(map.get(key));
				result.add(rr);
			}
		}

		Collections.sort(result, new Comparator<Resource>() {

			@Override
			public int compare(Resource o1, Resource o2) {
				// TODO Auto-generated method stub
				return o1.getIndexs().compareTo(o2.getIndexs());
			}
		});

		return result;
	}

	/**
	 * 添加管理员
	 * 
	 * @return
	 */
	@Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
	public boolean addAdmin(Admin admin) {
		String roleIds = admin.getRoleIds();
		int res = adminMapper.addAdmin(admin);
		if (res > 0) {
			if (roleIds != null && roleIds != "") {
				String[] values = roleIds.split(",");
				for (String s : values) {
					if (s != "") {
						adminMapper.addUserRole(admin.getId(),
								Integer.parseInt(s));
					}
				}
			}
		}
		return res > 0;
	}

	/**
	 * 删除管理员
	 */
	@Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
	public boolean delAdminById(Integer id) {
		int res = adminMapper.delAdminById(id);
		if (res > 0) {
			adminMapper.deleteAuserRoleByUserId(id);
		}
		return res > 0;
	}

	/**
	 * 禁止登录管理员
	 * 
	 * @return
	 */
	public boolean updateAdminStatus(Integer id, Integer status) {
		return adminMapper.updateAdminStatus(id, status) > 0;
	}

	/**
	 * 更新管理员密码
	 * 
	 * @return
	 */
	public boolean updateAdminPwd(Integer id, String pwd) {
		return adminMapper.updateAdminPwd(id, pwd) > 0;
	}

	public List<TreeNode> getTreeByUserId(Integer userId) {
		// TODO Auto-generated method stub
		Admin admin = adminMapper.getAdminById(userId);
		List<Resource> resources = null;
		if (admin.getRoleCode() != 2) {
			List<AUserRole> list = adminMapper.getRoleIdByUserId(userId);
			List<Integer> ids = new ArrayList<Integer>();
			for (AUserRole r : list) {
				ids.add(r.getRoleId());
			}

			if (!ids.isEmpty()) {
				resources = resourceMapper.getModelListByRoleId(StringUtils
						.join(ids, ","));
			}
		} else {
			resources = resourceMapper.getAllResource();
		}

		List<TreeNode> resultList = new ArrayList<TreeNode>();
		TreeNode node = null;
		for (Resource r : resources) {
			node = new TreeNode();
			node.setId(r.getId());
			node.setpId(r.getParentId());
			node.setName(r.getName());
			resultList.add(node);
		}
		return resultList;
	}

	public List<Resource> getResource(PageModel pageModel) {
		int count = resourceMapper.countResource();
		pageModel.setRecordCount(count);
		return resourceMapper.getResource(pageModel);
	}

	public Resource getResourceById(Integer id) {
		// TODO Auto-generated method stub
		return resourceMapper.getResourceById(id);
	}

	public Integer saveResource(Resource entity) {
		// TODO Auto-generated method stub
		return resourceMapper.saveResource(entity);
	}

	public Integer updateResource(Resource entity) {
		// TODO Auto-generated method stub
		return resourceMapper.updateResource(entity);
	}

	@Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
	public Integer deleteResource(Long resourceId) {
		// TODO Auto-generated method stub
		int res = resourceMapper.deleteResource(resourceId);
		if (res > 0) {
			resourceMapper.delRelationByResourceId(resourceId);
		}
		return res;
	}

	public Admin getAdminById(Integer id) {
		// TODO Auto-generated method stub
		return adminMapper.getAdminById(id);
	}

	@Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
	public boolean editAdmin(Admin admin) {
		// TODO Auto-generated method stub
		Admin a = adminMapper.getAdminById(admin.getId());
		if (admin.getPwd() == null || admin.getPwd() == "") {
			admin.setPwd(a.getPwd());
		} else {
			admin.setPwd(CryptUtil.md5(admin.getPwd()));
		}
		int res = adminMapper.updateAdmin(admin);
		String roleIds = admin.getRoleIds();
		if (res > 0) {
			if (roleIds != null && roleIds != "") {
				adminMapper.deleteAuserRoleByUserId(admin.getId());
				String[] values = roleIds.split(",");
				for (String s : values) {
					if (s != "") {
						adminMapper.addUserRole(admin.getId(),
								Integer.parseInt(s));
					}
				}
			}
		}
		return res > 0;
	}

	public List<Integer> getRoleIdByUserId(Integer userId) {
		// TODO Auto-generated method stub
		List<AUserRole> list = adminMapper.getRoleIdByUserId(userId);
		List<Integer> result = new ArrayList<Integer>();
		for (AUserRole role : list) {
			result.add(role.getRoleId());
		}
		return result;
	}

	public List<Role> getAllAUserRole() {
		// TODO Auto-generated method stub
		return adminMapper.getAllAuRoles();
	}

	public List<Resource> getResourceByRoleId(Integer roleId) {
		// TODO Auto-generated method stub
		return resourceMapper.getModelListByRoleId(String.valueOf(roleId));
	}

	public List<Role> getRole(PageModel pageModel) {
		// TODO Auto-generated method stub
		int count = adminMapper.getRoleCount();
		pageModel.setRecordCount(count);
		return adminMapper.getRole(pageModel);
	}

	@Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
	public boolean addRole(Role role) {
		// TODO Auto-generated method stub
		int res = adminMapper.addRole(role);
		String resourcesIds = role.getResourcesIds();
		if (res > 0) {
			if (resourcesIds != null && resourcesIds != "") {
				String[] ids = resourcesIds.split(",");
				for (String id : ids) {
					RoleResource ur = new RoleResource();
					ur.setRoleId(role.getId());
					ur.setResourceId(Integer.parseInt(id));
					resourceMapper.addAdminResource(ur);
				}
			}
		}
		return res > 0;
	}

	@Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
	public boolean editRole(Role role) {
		// TODO Auto-generated method stub
		int res = adminMapper.updateRole(role);
		String resourcesIds = role.getResourcesIds();
		if (res > 0) {
			resourceMapper.delAdminResourceByRoleId(role.getId());// 删除角色-资源关系
			if (resourcesIds != null && resourcesIds != "") {
				String[] ids = resourcesIds.split(",");
				for (String id : ids) {
					RoleResource ur = new RoleResource();
					ur.setRoleId(role.getId());
					ur.setResourceId(Integer.parseInt(id));
					resourceMapper.addAdminResource(ur);
				}
			}
		}
		return res > 0;
	}

	@Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
	public boolean delRoleById(Integer id) {
		// TODO Auto-generated method stub
		int res = adminMapper.delRoleById(id);
		if (res > 0) {
			adminMapper.deleteAuserRoleByRoleId(id);// 删除角色-用户关系
			resourceMapper.delAdminResourceByRoleId(id);// 删除角色-资源关系

		}
		return res > 0;
	}

	public Role getRoleById(Integer id) {
		// TODO Auto-generated method stub
		return adminMapper.getRoleById(id);
	}

	// public Admin getUserInfo(String username, String pwd) {
	// Admin admin = adminMapper.getAdminByUsername(username);// 从DB获取admin
	// if (admin != null && admin.getPwd().equals(pwd)) {
	// List<AuserShop> shops = adminMapper.getAuserShopsByAuserId(admin
	// .getId());
	// List<AuserShopAudio> audios = adminMapper
	// .getAuserAudioByAuserId(admin.getId());
	// admin.setShops(shops);
	// admin.setAudios(audios);
	// return admin;
	// }
	// return null;
	// }
}
